package com.atguigu.tingshu.user.login.client;

import com.atguigu.tingshu.user.login.annotation.DifWaysLogin;
import com.atguigu.tingshu.user.login.domain.ILogin;
import com.atguigu.tingshu.user.login.enums.LoginType;
import com.atguigu.tingshu.vo.user.LoginVo;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class LoginClient implements ApplicationContextAware {
    private static final Map<Integer, ILogin> loginMap = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //获取所有带有DifWaysLogin注解的bean
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(DifWaysLogin.class);
        if (!CollectionUtils.isEmpty(beansWithAnnotation)) {
            beansWithAnnotation.values().forEach(bean -> {
                DifWaysLogin difWaysLogin = bean.getClass().getAnnotation(DifWaysLogin.class);
                loginMap.put(difWaysLogin.value().getType(), (ILogin) bean);
            });
        }
    }

    public Map<String, String> login (LoginType loginType, LoginVo loginVo){
        return loginMap.get(loginType.getType()).login(loginVo);
    }

}
